package com.yxinsur.imc.business.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yxinsur.imc.business.domain.ImcBroker;
import com.yxinsur.imc.business.domain.ImcBrokerPersistencyRate;
import com.yxinsur.imc.business.enums.IsDeletedEnum;
import com.yxinsur.imc.business.enums.PersistencyRateTypeEnum;
import com.yxinsur.imc.business.enums.YesOrNoEnum;
import com.yxinsur.imc.business.form.BrokerPersistencyRateCalculateForm;
import com.yxinsur.imc.business.form.BrokerPersistencyRateForm;
import com.yxinsur.imc.business.mapper.ImcBrokerMapper;
import com.yxinsur.imc.business.mapper.ImcBrokerPersistencyRateMapper;
import com.yxinsur.imc.business.service.IImcBrokerPersistencyRateService;
import com.yxinsur.imc.business.vo.BrokerPersistencyRateVo;
import com.yxinsur.imc.common.utils.DateUtils;
import com.yxinsur.imc.common.utils.SecurityUtils;
import com.yxinsur.imc.common.validator.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 代理人继续率
Service业务层处理
 * 
 * @author imc
 * @date 2021-05-20
 */
@Service
public class ImcBrokerPersistencyRateServiceImpl extends ServiceImpl<ImcBrokerPersistencyRateMapper, ImcBrokerPersistencyRate> implements IImcBrokerPersistencyRateService
{
    @Autowired
    private ImcBrokerPersistencyRateMapper imcBrokerPersistencyRateMapper;
    @Autowired
    private ImcBrokerMapper imcBrokerMapper;

    /**
     * 查询代理人继续率列表
     * 
     * @param brokerPersistencyRateForm 代理人继续率
     * @return 代理人继续率
     */
    @Override
    public List<BrokerPersistencyRateVo> selectImcBrokerPersistencyRateList(BrokerPersistencyRateForm brokerPersistencyRateForm)
    {
        return imcBrokerPersistencyRateMapper.selectImcBrokerPersistencyRateList(brokerPersistencyRateForm,SecurityUtils.getTenantId());
    }

    /**
     * 计算代理人继续率
     *
     * @param brokerPersistencyRateCalculateForm 代理人继续率
     * @return 结果
     */
    @Override
    @Transactional
    public int calculate(BrokerPersistencyRateCalculateForm brokerPersistencyRateCalculateForm)
    {
        Assert.isBlank(brokerPersistencyRateCalculateForm.getPersistencyMonth(),"计算月度不能为空");
        Assert.isBlank(brokerPersistencyRateCalculateForm.getPersistencyRateType(),"继续率类型为必选项");
        Date date = DateUtils.getNowDate();

        Integer policyYear = 0;
        String persistencyRateType = brokerPersistencyRateCalculateForm.getPersistencyRateType();
        if(persistencyRateType.equals(PersistencyRateTypeEnum.R13.getCode())){
            policyYear = 1;
        }else if(persistencyRateType.equals(PersistencyRateTypeEnum.R25.getCode())){
            policyYear = 2;
        }else if(persistencyRateType.equals(PersistencyRateTypeEnum.R37.getCode())){
            policyYear = 3;
        }else if(persistencyRateType.equals(PersistencyRateTypeEnum.R49.getCode())){
            policyYear = 4;
        }
        Date monthDate = DateUtils.addMonths(DateUtils.parseDate(brokerPersistencyRateCalculateForm.getPersistencyMonth()+"-01"),-2);
        List<Map<String,Object>> list = this.imcBrokerPersistencyRateMapper.calculateBrokerPersistencyRateList(DateUtil.format(monthDate,"yyyy-MM-dd"),policyYear,SecurityUtils.getTenantId());
        Map<Long,Map<String,Object>> rateMap = new HashMap<>();
        list.stream().forEach(map -> rateMap.put((long)map.get("brokerId"),map));

        String username = SecurityUtils.getUsername();
        Long tenantId = SecurityUtils.getTenantId();
        QueryWrapper<ImcBroker> brokerQueryWrapper = new QueryWrapper<>();
        brokerQueryWrapper.eq("is_deleted",IsDeletedEnum.N.getCode());
        brokerQueryWrapper.eq("status", YesOrNoEnum.Y.name());
        brokerQueryWrapper.eq("tenant_id",SecurityUtils.getTenantId());
        List<ImcBroker> brokers = this.imcBrokerMapper.selectList(brokerQueryWrapper);
        for (ImcBroker broker:brokers) {
            ImcBrokerPersistencyRate rate = new ImcBrokerPersistencyRate();
            Map<String,Object> map = rateMap.get(broker.getId());
            if(map != null){
                rate.setPersistencyRate(new BigDecimal(map.get("persistencyRate").toString()));
                rate.setPayablePrem(new BigDecimal(map.get("payablePrem").toString()));
                rate.setPaymentPrem(new BigDecimal(map.get("paymentPrem").toString()));
                rate.setPayableOrderRiskJson(map.get("payableOrderRiskJson").toString());
            }else{
                rate.setPersistencyRate(BigDecimal.ZERO);
                rate.setPayablePrem(BigDecimal.ZERO);
                rate.setPaymentPrem(BigDecimal.ZERO);
            }
            rate.setBrokerId(broker.getId());
            rate.setPersistencyMonth(brokerPersistencyRateCalculateForm.getPersistencyMonth());
            rate.setPersistencyRateType(persistencyRateType);
            rate.setCreateId(username);
            rate.setCreateTime(date);
            rate.setIsDeleted(IsDeletedEnum.N.getCode());
            rate.setTenantId(tenantId);
            this.saveOrUpdateRate(rate);
        }
        return list.size();
    }

    /**
     * 新增或更新费率
     * @param rate
     */
    private void saveOrUpdateRate(ImcBrokerPersistencyRate rate)
    {
        QueryWrapper<ImcBrokerPersistencyRate> persistencyRateQueryWrapper = new QueryWrapper<>();
        persistencyRateQueryWrapper.eq("broker_id",rate.getBrokerId());
        persistencyRateQueryWrapper.eq("persistency_month",rate.getPersistencyMonth());
        persistencyRateQueryWrapper.eq("persistency_rate_type",rate.getPersistencyRateType());
        persistencyRateQueryWrapper.eq("is_deleted",IsDeletedEnum.N.getCode());
        persistencyRateQueryWrapper.eq("tenant_id",SecurityUtils.getTenantId());
        List<ImcBrokerPersistencyRate> list =  this.imcBrokerPersistencyRateMapper.selectList(persistencyRateQueryWrapper);
        if(list.size() == 0){
            this.imcBrokerPersistencyRateMapper.insert(rate);
        }else{
            ImcBrokerPersistencyRate persistencyRate = list.get(0);
            persistencyRate.setPersistencyRate(rate.getPersistencyRate());
            persistencyRate.setPayableOrderRiskJson(rate.getPayableOrderRiskJson());
            persistencyRate.setPayablePrem(rate.getPayablePrem());
            persistencyRate.setPaymentPrem(rate.getPaymentPrem());
            persistencyRate.setUpdateId(rate.getCreateId());
            persistencyRate.setUpdateTime(rate.getCreateTime());
            this.imcBrokerPersistencyRateMapper.updateById(persistencyRate);
        }
    }
    /**
     * 修改代理人继续率
     *
     * @param imcBrokerPersistencyRate 代理人继续率
     * @return 结果
     */
    @Override
    public int updateImcBrokerPersistencyRate(ImcBrokerPersistencyRate imcBrokerPersistencyRate)
    {
        imcBrokerPersistencyRate.setUpdateTime(DateUtils.getNowDate());
        return 0;
    }

    /**
     * 批量删除代理人继续率
     *
     * @param ids 需要删除的代理人继续率
     * @return 结果
     */
    @Override
    public int deleteImcBrokerPersistencyRateByIds(String[] ids)
    {
        return 0;
    }
}
